<?php

class simpleTable
{
	protected $_code			= null;
	protected $_submit			= null;
	protected $_submitName		= null;
	protected $_data			= null;
	protected $_colWidth		= null;
	protected $_columns			= null;
	protected $_labels			= null;
	protected $_nRows			= null;
	protected $_nColumns		= null;
	protected $_headerMessage	= null;
	protected $_hiddens			= null;
	protected $_headerAlign		= null;
	protected $_wantForm 		= null;
	protected $_formMethod		= null;
	protected $_allColspan		= null;
	protected $_viewLabel 		= null;
	protected $_id				= null;
	protected $_scrollPage		= null;
	protected $_viewForm		= null;

	protected $_firstLabelColspan = null;
	protected $_rowsCode		  = null;
	protected $_rowsStyle		  = null;
	protected $_identifier		  = null;

	function __construct($class=null,$border=null,$cellspacing=null,$cellpadding=null,$width=null,$height=null){
		$this->_data = array ('cellspacing'=>0,
								'cellpadding'=>1,
								'border'=>0,
								'width'=>'100%',
								'height'=>'',
								'class'=>'',
								'align'=>'left',
								'name'=>'generic');

		$this->_firstLabelColspan = 1;
		$this->_submit = false;
		$this->_hiddens = array();
		$this->_headerAlign = 'left';
		$this->_labels = '';
		$this->_id = $this->_data['name'];
		$this->_nColumns = 1;
		$this->_nRows = 1;
		$this->_wantForm = true;
		$this->_formMethod = 'POST';
		$this->_viewLabel = true;
		$this->_identifier = 'htmlTable';
		$this->_formAction = $_SERVER['REQUEST_URI'];
	}
	
	public function setScrollPage($total, $page, $count, $link){
		global $hikarilanguage, $lang;
		$page = max(1,$page);
		$lang = $hikarilanguage[$lang];
		$nPages = ceil($total / $count);
		$nPages = max ($nPages,1);
		$link = preg_replace ('/\/page[0-9]+/','',$link);
		$minPage = max(1,$page-1);
		$maxPage = min($nPages,$page+1);
		$prevHrefLink = str_replace ('//','/',$link.'/page'.$minPage);
		$nextHrefLink = str_replace ('//','/',$link.'/page'.$maxPage);
		$prevLink = '<a href="'.$prevHrefLink.'">&laquo;</a>';
		$nextLink = '<a href="'.$nextHrefLink.'">&raquo;</a>';
		
		$input = '<input type="text" size="1" style="font-size:9px;" value="'.$page.'" id="scrollPage_page" /> <input type="button" value="&raquo;" onClick="document.location.href = \''.$link.'/page\'+document.getElementById(\'scrollPage_page\').value;" style="cursor:pointer;" />';
		$this->_scrollPage = $prevLink.' '.$lang['page'].' <b>'.$page.'</b>/'.$nPages.' '.$nextLink.' '.$input;
	}

	public function setSubmit($bol,$name = null){
		$this->_submit = $bol;
		$this->_submitName = $name;
	}
	
	public function viewSubmit($bol){
		$this->_submit = $bol;
	}
	
	public function setId($id){
		$this->_id = $id;
	}

	public function setFormMethod($me){
		$this->_formMethod = $me;
	}
	
	public function setFormAction($action){
		$this->_formAction = $action;
	}

	public function showForm($bol){
		$this->_wantForm = $bol;
		$this->_submit = $bol;
	}

	public function setCellspacing($value){
		$this->_data['cellspacing'] = $value;
	}

	public function setCellpadding($value){
		$this->_data['cellpadding'] = $value;
	}

	public function setWidth($value){
		if (!strpos('px')) $value = $value .= 'px';
		$this->_data['width'] = $value;
	}

	public function setHeight($value){
		$this->_data['height'] = $value;
	}

	public function setAlign($value){
		$this->_data['align'] = $value;
	}

	public function setClass($value){
		$this->_data['class'] = $value;
	}

	public function setName($name){
		$this->_data['name'] = $name;
	}

	public function setIdentifier($trigger){
		$this->_identifier = $trigger;
	}

	public function setColWidth($width){
		$this->_colWidth = $width;
	}

	public function setColColspan($colspan){
		$this->_allColspan = $colspan;
	}

	public function setHeaderMessage($message){
		$this->_headerMessage = $message;
	}

	public function setHeaderAlign($align){
		$this->_headerAlign = $align;
	}

	public function setLabels($labels){
		$this->_nColumns = count($labels);
		if (is_null($this->_allColspan))
			$this->_allColspan = array_fill(0,$this->_nColumns,1);

		$count = 0;
		foreach ($labels as $singleLabel){
			$count++;
			$cell = new cellLabel($singleLabel);
			$cell->setWidth($this->_colWidth[$count-1]);
			$cell->setColspan($this->_allColspan[$count-1]);
			$this->_labels .= $cell->getCode();
		}
	}

	public function viewLabel($bol){
		$this->_viewLabel = $bol;
	}

	public function addHidden ($name,$value){
		$this->_hiddens[$name] = $value;
	}

	public function getCode (){
		self::__buildCode();
		return $this->_code;
	}

	protected function __buildCode(){

		$formCode =  '<form method="'.$this->_formMethod.'" action="'.$this->_formAction.'" name="'.$this->_data['name'].'">
					  	 <input type="hidden" value="1" name="doaction" />
					  	 <input type="hidden" value="" name="posted_value" />
					  	 <input type="hidden" value="'.$this->_identifier.'" name="trigger" />[[hiddens]][[tablecode]]</form>';
		$hiddens = '';
		foreach ($this->_hiddens as $name=>$value)
			$hiddens .= '<input id="hidden_'.$name.'" type="hidden" value="'.$value.'" name="'.$name.'" />';
    	$this->_code  = '<div class="hikariTableHeaderMessage">'.$this->_headerMessage.'</div>';
    	if (!is_null($this->_scrollPage))
    		$this->_code  .= '<div class="hikariTableScrollPage">'.$this->_scrollPage.'</div>';			
    	
		$this->_code  .= '<table id="'.$this->_id.'" class="hikariMasterTable '.$this->_data['class'].'" border="'.$this->_data['border'].'"  cellspacing="'.$this->_data['cellspacing'].'" cellpadding="'.$this->_data['cellpadding'].'" align="'.$this->_data['align'].'" style="width:'.$this->_data['width'].';height:'.$this->_data['height'].'">';
		if ($this->_viewLabel)
			$this->_code .= $this->__manageLabels();
		$this->_code .= $this->__manageRows();
		if ($this->_submit)
			$this->_code .= '<tr>
			                     '.((array_sum($this->_allColspan) == 1 ) ? '':'<td colspan="'.(array_sum($this->_allColspan) - 1).'">&nbsp;</td>').'
			                     <td class="center"><input type="submit" name="'.(is_null($this->_submitName) ? 'Submit':$this->_submitName).'" value="'.(is_null($this->_submitName) ? 'Submit':$this->_submitName).'" /></td>
			                 </tr>';
		$this->_code .='</table>';

		if ($this->_wantForm) {
			$this->_code = str_replace ('[[tablecode]]',$this->_code,$formCode);
			$this->_code = str_replace ('[[hiddens]]',$hiddens,$this->_code);
		}

	}

	public function addLabels($labels){
		$this->_labels = $labels;
		$this->_nColumns = $this->_labels->getCount();
	}

	public function addRow($objects,$class = null,$style = null, $id = null){
		$cellsCode = '';
		$counter = 0;
		foreach ($objects as $singleCell){			
			$currentColspan = $singleCell->getColspan();
			$realWidth = 0;
			//Fondo le width delle colonne in base al colspan della colonna corrente			
			for ($i=0;$i<$currentColspan;$i++)
				$realWidth += $this->_colWidth[$counter+$i]; 
			$counter+=$currentColspan;	
			if (is_null($singleCell->getWidth())) {
				$singleCell->setWidth($realWidth);
			}					
			$cellsCode .= $singleCell->getCode();			
			if ((get_class($singleCell) == 'buttonCell') && (!in_array($singleCell->getValue(),$this->_hiddens))) {
				$this->addHidden($singleCell->getValue(),'');
			}
		}
		$this->_nRows++;
		$this->_rowsCode[] = $cellsCode;
		$this->_rowsStyle[] = array($class,$style);
		$this->_rowsIds[] = $id;
	}

	protected function __manageLabels(){
		$code = '<tr class="hikariHeadRow">'.$this->_labels.'</tr>';
		return $code;
	}

	protected function __manageRows(){
		$code = '';
		for ($i=0,$limit = count($this->_rowsCode);$i<$limit;$i++){			
		  $rowStyle = $this->_rowsStyle[$i];
		  $id = (!is_null($this->_rowsIds[$i])) ?  $this->_rowsIds[$i] : 'row'.$i;
		  $code	.= '<tr id="'.$id.'" class="hikariNormalRow row'.($i%2).' '.(($rowStyle[0]!=null) ? $rowStyle[0]:'').'" style="'.(($rowStyle[1]!=null) ? $rowStyle[1]:'').'">';
		  $code .= $this->_rowsCode[$i];
		  $code .= '</tr>';
		}
		return $code;
	}
	
	public function buildFromQuery($res){
		global $hikariDB;
		$initial = true;
		
		if ($hikariDB->numRows($res) == 0){
			$uniqueRow = new textCell();
			$uniqueRow->setValue("no data");
			self::addRow(array($uniqueRow));
		}
		else {	
			while ($row = $hikariDB->fetchArray($res)){
				self::__autoBuildRow($row,$initial);
				$initial = false;
			}
		}
		self::__buildCode();		
	}
	
	public function buildFromMatrix($matrix){
		if (count($matrix) == 0){
			$uniqueRow = new textCell();
			$uniqueRow->setValue("no data");
			self::addRow(array($uniqueRow));
		}
		else {		
			$initial = true;
			foreach ($matrix as $row){
				self::__autoBuildRow($row,$initial);
				$initial = false;
			}
		}
		self::__buildCode();
	}
	
	private function __autoBuildRow($row,$initial){
		$row = self::__cleanArray($row);
		if ($initial){
			$totalCols = count(array_keys($row));
			$singleWidth = $this->_data['width'] / $totalCols; //da valutare
			self::setLabels(array_keys($row));
			$initial = false;
		}
		self::addRow(self::buildSingleRow($row));
	}
	
	private function __cleanArray($array){
		$final = array();
		foreach ($array as $index=>$value){
			if (!is_numeric($index)){
				$final[$index] = $value;
			}
		}
		return $final;
	}
	
	private function buildSingleRow($row){
		$rowArray = Array();
		foreach ($row as $cell){
			$cellValue = (is_null($cell)) ? 'NULL':$cell;
			$rowArray[] = new textCell(utf8_decode(stripslashes(html_entity_decode($cellValue))));
		}
		return $rowArray;
	}
	
}


class masterCell
{
	protected $_code		= null;
	protected $_value		= null;
	protected $_align		= null;
	protected $_vAlign		= null;
	protected $_colspan		= null;
	protected $_width		= null;
	protected $_name		= null;
	protected $_javascript  = null;
	protected $_style		= null;
	protected $_link		= null;
	protected $_linkTarget  = null;
	protected $_language	= null;
	protected $_id			= null;
	protected $_inputId		= null;
	protected $_inputStyle= null;

	function __construct(){
		global $hikarilanguage;
		$this->_language = $hikarilanguage[$GLOBALS['lang']];
		$this->_align = 'center';
		$this->_colspan = 1;
	}
	
	public function setInputId($id){
		$this->_inputId = $id;
	}

	public function setWidth($width){
		$this->_width = $width;
	}
	
	public function setId($id){
		$this->_id = $id;
	}

	public function getWidth(){
		return $this->_width;
	}

	public function setLink($link,$linkTarget = "_blank"){
		$this->_link = $link;
		$this->_linkTarget = $linkTarget;
	}

	public function setAlign($align){
		$this->_align = $align;
	}
	
	public function setValign($align){
		$this->_vAlign = $align;
	}

	public function setStyle($style){
		$this->_style = $style;
	}
	
	public function setClass($class){
		$this->_class = $class;
	}

	public function setJavascript($javascript){
		$this->_javascript = $javascript;
	}

	public function setValue($value){
		$this->_value = $value;
	}

	public function setName($name){
		$this->_name = $name;
	}

	public function setColspan($colspan){
		$this->_colspan = $colspan;
	}
	
	public function getColspan(){
		return $this->_colspan;
	}
	
	public function setInputStyle($style){
		$this->_inputStyle = $style;
	}

	protected function __buildCode(){
		$this->_code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.' '.$this->_vAlign.' '.$this->_class.'" style="width:'.$this->_width.';'.$this->_style.'" colspan="'.$this->_colspan.'" '.$this->_javascript.'>[[link]]'.$this->_value.'[[/link]]</td>';
		if (is_null($this->_link)){
		   $this->_code = str_replace ('[[link]]','',$this->_code);
		   $this->_code = str_replace ('[[/link]]','',$this->_code);
		}
		else {
			$this->_code = str_replace ('[[link]]','<a href="'.$this->_link.'" target="'.$this->_linkTarget.'">',$this->_code);
			$this->_code = str_replace ('[[/link]]','</a>',$this->_code);
		}
	}

	public function getCode(){
		self::__buildCode();
		if ($this->_value == 'empty')
			self::__emptyCode();
		return $this->_code;
	}

	public function getValue(){
		return $this->_value;
	}

	protected function __emptyCode(){
		$this->_code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.'" style="width:'.$this->_width.';'.$this->_style.'" colspan="'.$this->_colspan.'" '.$this->_javascript.'>&nbsp;</td>';
	}

}

class textCell extends masterCell
{

	function __construct($value = null){
		parent::__construct();
		$this->_value = $value;
	}

}

class separatorCell1 extends textCell
{

	function __construct($value = null){
		parent::__construct($value);
		$this->_class = 'hikariHRColumns1';		
	}		

}

class separatorCell2 extends textCell
{

	function __construct($value = null){
		parent::__construct($value);
		$this->_class = 'hikariHRColumns2';		
	}		

}

class treeCell extends textCell
{
	private $_maxLevel  = null;
	private $_emptySlot = null;
	private $_arrowSlot = null;
	private $_level		= null;

	function __construct($node,$maxLevel){
		parent::__construct();
		$this->_data = $node;
		if (count($node) == 1) {
		  $this->_data = array_pop($node);
		}
		$this->_align = 'left';
		$this->_level = $this->_data['nodelevel'];
		$this->_value = 'no value';
		$this->_maxLevel = $maxLevel;
		$this->_colspan = $maxLevel - $this->_level;
		$this->_emptySlot = max (0,$maxLevel - 2 - $this->_colspan);
	}

	public function setValue($value){
		$this->_value = $value;
	}

	private function __buildEmptyCode(){
		$code = '';
		if ($this->_emptySlot > 0)
			$code = '<td id="'.$this->_id.'" class="hikariNormalColumn" colspan="'.$this->_emptySlot.'" style="width:'.(20 * $this->_emptySlot).'px">&nbsp;</td>';
		return $code;
	}

	private function __buildPreCode(){
		$code = ($this->_level > 1) ? '<td class="child" style="width:20px;">&nbsp;</td>' : '';
		return $code;
	}

	public function setWidth($width){
		$this->_width = $width - (20 * $this->_emptySlot) - (20 * ($this->_maxLevel - $this->_colspan - 1) );
		$this->_width .= 'px';
	}

	protected function __buildCode(){

		$code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.'" style="width:'.$this->_width.';'.$this->_style.'" colspan="'.$this->_colspan.'" '.$this->_javascript.'>[[link]]'.$this->_value.'[[/link]]</td>';
		if (is_null($this->_link)){
		   $code = str_replace ('[[link]]','',$code);
		   $code = str_replace ('[[/link]]','',$code);
		}
		else {
			$code = str_replace ('[[link]]','<a href="'.$this->_link.'" >',$code);
			$code = str_replace ('[[/link]]','</a>',$code);
		}

		$this->_code = self::__buildEmptyCode().self::__buildPreCode().$code;
	}

	public function getCode(){
		self::__buildCode();
		return $this->_code;
	}


}

class cellLabel extends textCell
{
	private $_labels = null;

	public function __buildCode(){
		$this->_code = '<th id="'.$this->_id.'" class="hikariHeadColumn '.$this->_align.'" style="width:'.$this->_width.'" colspan="'.$this->_colspan.'">'.$this->_value.'</th>';
	}

	public function getCode(){
		self::__buildCode();
		return $this->_code;
	}
}


class buttonCell extends textCell
{

	protected $_postValue		= null;
	protected $_confirm			= null;
	protected $_confirmMessage  = null;

	function __construct($value = null,$postValue = null){
		parent::__construct();
		$this->_value = str_replace(' ' ,'_',$value);
		$this->_postValue = $postValue;
		$this->_confirmMessage = $this->_language['confirm'];
	}
		
	public function setPostValue($postValue){
		$this->_postValue = $postValue;
	}
	  
	public function setValue($value){
		$this->_value = str_replace(' ' ,'_',$value);
	}

	public function setConfirmMessage($message){
		$this->_confirmMessage = $message;
	}

	protected function __buildCode(){		
		$confirmCode = '';
		if ($this->_confirm)
			$confirmCode = "if (!confirm('".$this->_confirmMessage."')) return false;";
		
		$content = '<input style="'.$this->_inputStyle.'" type="submit" value="'.$this->_value.'"  '.$this->_javascript.' onClick="'.$confirmCode.'this.form.'.$this->_value.'.value = \''.$this->_postValue.'\';this.form.posted_value.value = \''.$this->_postValue.'\';">';
		$this->_code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.'" style="width:'.$this->_width.'" colspan="'.$this->_colspan.'">'.(($this->_value == 'empty') ? '' : $content).'</td>';
	}

	public function setConfirm($bol){
		$this->_confirm = $bol;
	}

	public function getCode(){
		self::__buildCode();
		if ($this->_value == 'empty')
			self::__emptyCode();
		return $this->_code;
	}
}

class inputCell extends buttonCell
{

	protected $_size = null;
	protected $_ro	 = null;
	
	function __construct($value = null,$name = null){
		parent::__construct();
		$this->_value = $value;
		$this->_name  = $name;
		$this->_type  = 'text';
		$this->_size  = 10;
		$this->_ro	  = false;
	}
	
	public function setSize($size){
		$this->_size = $size;
	}
	
	public function setReadonly($ro){
		$this->_ro = $ro;
	}
	
	public function getCode(){
		if ($this->_value == 'empty')
			self::__emptyCode();
		else {
			$this->_code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.'" style="width:'.$this->_width.';'.$this->_style.'" colspan="'.$this->_colspan.'" '.$this->_javascript.'>
								<input '.(($this->_ro) ? 'readonly="readonly"' : '').' size="'.$this->_size.'" style="'.$this->_inputStyle.'" id="'.$this->_inputId.'" type="'.$this->_type.'" name="'.$this->_postValue.'" value="'.$this->_value.'" />
						    </td>';
		}
		return $this->_code;
	}

}

class checkboxCell extends buttonCell
{

	protected $_checked = null;

	function __construct($value = null,$checked = null){
		parent::__construct();
		$this->_value = $value;
		$this->_checked = $checked;
		$this->_type = 'checkbox';
	}
	
	public function setType($type){
		$this->_type = $type;
	}
	
	public function setChecked($checked){
		$this->_checked = $checked;
	}		

	public function setName($name){
		$this->_postValue = $name;
	}

	public function setValue($value,$checked = false){
		$this->_value = $value;
		$this->_checked = $checked;
	}

	protected function __buildCode(){

		$this->_code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.'" style="width:'.$this->_width.';'.$this->_style.'" colspan="'.$this->_colspan.'" '.$this->_javascript.'>
							<input style="'.$this->_inputStyle.'" id="'.$this->_inputId.'" type="'.$this->_type.'" name="'.$this->_postValue.'[]" value="'.$this->_value.'" '.(($this->_checked) ? 'checked="checked"' : '').'/>
					    </td>';
		
	}

	public function getCode(){
		self::__buildCode();
		if ($this->_value == 'empty')
			self::__emptyCode();
		return $this->_code;
	}

}

class selectCell extends masterCell
{
	
	private $_options 	= null;
	private $_selName	= null;
	
	function __construct($value = null){
		parent::__construct();
		$this->_border = 0;
		$this->_value = $value;
	}
	
	public function setSelName($name){
		$this->_selName = $name;
	}
	
	public function setOptions($values){
		$this->_options = $values;
	}
	
	public function addOption($key,$value){
		$this->_options[$key] = $value;
	}
	
	protected function __buildCode(){
		$optCode = "";
		
		foreach ($this->_options as $key=>$value){
			$sel = ($key == $this->_value) ? 'selected="selected"' : '';
			$optCode .= '<option value="'.$key.'" '.$sel.'>'.$value.'</option>';
		}

		$this->_code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.'" style="width:'.$this->_width.';'.$this->_style.'" colspan="'.$this->_colspan.'" '.$this->_javascript.'>
							<select name="'.$this->_selName.'" style="'.$this->_inputStyle.'">
								'.$optCode.'
							</select>
					    </td>';
	}

	public function getCode(){
		self::__buildCode();
		if ($this->_value == 'empty')
			self::__emptyCode();
		return $this->_code;
	}
	
}

class imgCell extends masterCell
{
	private $_border 		= null;
	private $_imgWidth 		= null;
	private $_imgHeight 	= null;
	private $_title 		= null;
	private $_description 	= null;
	private $_path 	= null;

	function __construct($value = null){
		parent::__construct();
		$this->_border = 0;
		$this->_value = $value;
	}

	public function setTitle($title){
		$this->_title = $title;
	}

	public function setPath($path){
		$this->_path = $path.((substr($path,-1)=='/')?'':'/');
	}

	public function setValue($value,$title){
		$this->_title = $title;
		$this->_value = $value;
	}

	public function setDescription($des){
		$this->_description = $des;
	}

	public function setBorder($border){
		$this->_border = $border;
	}

	public function setImgWidth($width){
		$this->_imgWidth = $width;
	}

	public function setImgHeight($height){
		$this->_imgHeight = $height;
	}

	protected function __buildCode(){
		if ($this->_value == 'null' || $this->_value == 'empty')
			self::__emptyCode();
		else {
			$sizeCodeW = !is_null($this->_imgWidth) ? 'width="'.$this->_imgWidth.'px"' : '';
			$sizeCodeH = !is_null($this->_imgHeight) ? 'height="'.$this->_imgHeight.'px"' : '';
			$this->_code = '<td id="'.$this->_id.'" class="hikariNormalColumn '.$this->_align.' '.$this->_vAlign.'" style="width:'.$this->_width.';'.$this->_style.'" colspan="'.$this->_colspan.'" '.$this->_javascript.'>[[link]]<img src="'.$this->_path.$this->_value.'" '.$sizeCodeH.' '.$sizeCodeW.' border="'.$this->_border.'" title="'.$this->_title.'" />[[/link]]<br> <span class="hikariImgDes">[[link]]<b>'.$this->_description.'</b>[[/link]]</span></td>';
			if (is_null($this->_link)){
			   $this->_code = str_replace ('[[link]]','',$this->_code);
			   $this->_code = str_replace ('[[/link]]','',$this->_code);
			}
			else {
				$this->_code = str_replace ('[[link]]','<a href="'.$this->_link.'" target="'.$this->_linkTarget.'">',$this->_code);
				$this->_code = str_replace ('[[/link]]','</a>',$this->_code);
			}
		}
	}

	public function getCode(){
		self::__buildCode();
		return $this->_code;
	}
}

?>